/*
 * Copyright (C) 2016 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.mapsdkexample.routeplan;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapsdkexample.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.leancloud.AVLogger;
import cn.leancloud.AVOSCloud;
import cn.leancloud.AVObject;
import cn.leancloud.AVQuery;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 此demo用来展示如何进行公交路线搜索并在地图使用RouteOverlay、TransitOverlay绘制
 * 同时展示如何进行节点浏览并弹出泡泡
 */
public class GetTimeMatrixActivity extends AppCompatActivity
        implements OnGetRoutePlanResultListener{

    private int qiyicount = 0;
    private int maxsize = 160;
    private int[][] timebox = new int[maxsize][maxsize];
    private HashMap<Integer, String> hashMap = new HashMap<Integer, String>();//使用hash表让名称和序号对应

    private RouteLine mRouteLine = null;
    private List<AVObject> pointInfoList;
    private List<AVObject> listTimebox;

    // 搜索相关
    private RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用

    private List<? extends RouteLine> mRouteLines;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_time_matrix);

        Log.d("which", "TransitRoutePlanActivity");

        for (int i = 0; i < maxsize; i++)
            for (int j = 0; j < maxsize; j++)
                timebox[i][j] = -1;

        //leancloud初始化
        AVOSCloud.setLogLevel(AVLogger.Level.DEBUG);
        AVOSCloud.initialize(
                this,
                "gYKKKJUqrlSsLCUDRD1aNRHj-gzGzoHsz",
                "viezs5eeEG4dLaPay20EaEXd",
                "dwxr3lun.api.lncld.net");

        //从数据库获得数据
        AVQuery<AVObject> query = new AVQuery<>("ViewpointInfo");
        //query.whereContains("tag", "风景区");
        query.limit(150);
        query.findInBackground().subscribe(new Observer<List<AVObject>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<AVObject> avObjects) {
                System.out.println("------------------------------" + avObjects.size());
                pointInfoList = avObjects;
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                apinit();
            }
        });

        //从数据库获得数据
        AVQuery<AVObject> querytimebox = new AVQuery<>("timebox");
        querytimebox.limit(150);
        querytimebox.orderByAscending("id");//按照id排序，id的数字对应于ViewpointInfo中的景点名称
        querytimebox.findInBackground().subscribe(new Observer<List<AVObject>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<AVObject> avObjects) {
                System.out.println("-----------------------------timebox----" + avObjects.size());
                listTimebox = avObjects;

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                timboxinit();
            }
        });

        // 初始化搜索模块，注册事件监听
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);

        initView();
    }

    //先找到各种控件
    private void initView() {
        Log.d("temp", "TransitRoutePlanActivity--initView");
    }

    //从数据库读入时间表信息
    public void timboxinit(){
        for (int i = 0; i < pointInfoList.size(); i++) {
            //System.out.println("i= "+i+listTimebox.get(i).getString("name")+listTimebox.get(i).getInt("0"));
            for (int j=0;j<i;j++)
            {
                timebox[i][j]=listTimebox.get(i).getInt(String.valueOf(j));
            }
        }
    }

    public void searchButtonProcess(View v) {
        AnPai();
    }

    private ArrayList<PlanNode> planNodes = new ArrayList<PlanNode>();
    private int xx = 0, yy = 0;

    public void apinit() {
        if (mRouteLines != null) {
            // 重置路线数据
            mRouteLines.clear();
            mRouteLines = null;
        }
        for (int i = 0; i < pointInfoList.size(); i++) {
            hashMap.put(1, pointInfoList.get(i).getString("name"));

            planNodes.add(PlanNode.withLocation(new LatLng(pointInfoList.get(i).getDouble("lat"), pointInfoList.get(i).getDouble("lng"))));

            Log.d("mytemp", pointInfoList.get(i).getString("name")
                    + " lat:" + pointInfoList.get(i).getDouble("lat")
                    + " lng:" + pointInfoList.get(i).getDouble("lng"));
        }
    }

    public void AnPai() {
        if (xx >= pointInfoList.size() - 1 && yy >= pointInfoList.size() - 2) {
            xx = 0;
            yy = 0;
            Log.d("mytemp","over-----");
            return;
        }
        yy++;
        if (yy >= xx) {
            xx++;
            yy = 0;
        }
        if (timebox[xx][yy] == -1) {
            //
            //
            //发起换乘路线规划
            mSearch.transitSearch(new TransitRoutePlanOption().from(planNodes.get(xx)).to(planNodes.get(yy)).city("北京"));//查找----------------------------------------------------------------
        }
        else{
            AnPai();
        }
    }
    
    //search完成后使用结果监听器解析获得的result
    @Override
    public void onGetTransitRouteResult(TransitRouteResult result) {
        //Log.d("temp", "结果监听器  " + result.error);
        if (result != null && result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            qiyicount++;
            // 起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            Toast.makeText(GetTimeMatrixActivity.this, "起终点或途经点地址有岐义，通过result.getSuggestAddrInfo()接口获取建议查询信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            qiyicount++;
            Toast.makeText(GetTimeMatrixActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
            Log.d("mytemp", pointInfoList.get(xx).getString("name") + "---"
                    + pointInfoList.get(yy).getString("name") + "  error");
            timebox[xx][yy] =-2;
            AnPai();
            return;
        }

        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            if (mRouteLines != null) {
                mRouteLines.clear();
            }
            mRouteLines = result.getRouteLines();//返回一个列表
            //
            //
            //
            //暂时取第一个搜索结果----------------------------------------------------------------------------------------------------------------------
            for (int position = 0; position < 1; position++) {
                if (mRouteLines == null) {
                    return;
                }
                mRouteLine = mRouteLines.get(position);

                Log.d("mytemp", pointInfoList.get(xx).getString("name") +xx+ " --- "
                        +yy + pointInfoList.get(yy).getString("name") + "  " + mRouteLine.getDuration());

                timebox[xx][yy] = mRouteLine.getDuration();
                AnPai();
            }
        }
    }

    public void uploadButtonProcess(View v) {
        for (int i = 0; i < pointInfoList.size(); i++) {
            // 构建对象
            AVObject todo = new AVObject("timebox");//--------------------------------------------------

            Log.d("uploadtemp","1");

            // 为属性赋值
            todo.put("id",i);
            todo.put("name", pointInfoList.get(i).getString("name"));
            for (int j = 0; j < pointInfoList.size(); j++)
                todo.put(String.valueOf(j), timebox[i][j]);

            Log.d("uploadtemp","2");

            // 将对象保存到云端
            todo.saveInBackground().subscribe(new Observer<AVObject>() {
                public void onSubscribe(Disposable disposable) {
                }

                public void onNext(AVObject todo) {
                    // 成功保存之后，执行其他逻辑
                    Log.d("temp", "保存成功。objectId：" + todo.getObjectId());
                }

                public void onError(Throwable throwable) {
                    Log.d("temperror", todo.getString("name"));
                    // 异常处理
                }

                public void onComplete() {
                }
            });

            try {
                Thread.currentThread().sleep(50);//设置主线程延迟，给后台存储留间隙
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void showButtonProcess(View v) {
        for (int i = 0; i < pointInfoList.size(); i++) {
            System.out.print("["+i+"]  ");
            for (int j = 0; j < pointInfoList.size(); j++) {
                System.out.print(" " + timebox[i][j]);
            }
            System.out.println(" ");
        }
        System.out.println("-----------------------------------" + qiyicount + "-------------------------");
        System.out.println("---" + pointInfoList.size() + "---");
        qiyicount = 0;
    }


    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult result) {
        Log.d("temp", "TransitRoutePlanActivity--onGetWalkingRouteResult(empty)");
    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult result) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult result) {

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放检索对象
        if (mSearch != null) {
            mSearch.destroy();
        }
    }
}
